# Contributor: Stefan Wagner <stw@bit-strickerei.de>
# Maintainer: Marian Buschsieweke <marian.buschsieweke@ovgu.de>
# Based on binutils-avr
_pkgbase=binutils
pkgname="$_pkgbase-cross-embedded"
pkgver=2.41
pkgrel=0
pkgdesc="tools necessary to build programs for embedded targets"
url="https://www.gnu.org/software/binutils/"
makedepends="gettext libtool autoconf automake bison texinfo zlib-dev zstd-dev"
arch="aarch64 armv7 ppc64le x86_64 x86"
license="GPL-2.0 GPL-3.0-or-later LGPL-2.0 BSD"
source="https://ftp.gnu.org/gnu/$_pkgbase/$_pkgbase-$pkgver.tar.xz"
builddir="$srcdir/$_pkgbase-$pkgver"

# classify targets as exotic or mainstream. Only build support for
# exotic targets on typical developer / CI hardware (x86_86, aarach64).
_targets_mainstream="
	arm-none-eabi
	avr
	riscv-none-elf
	"

_targets_exotic="
	msp430-elf
	or1k-elf
	aarch64-none-elf
	"

case "$CARCH" in
x86_64|aarch64)
	# support all targets on typical workstation / notebook / CI servers
	_targets="$_targets_mainstream $_targets_exotic"
	;;
*)
	# support only mainstream targets on exotic hosts
	_targets="$_targets_mainstream"
	;;
esac

for target in $_targets; do
	targetnorm="${target//-/_}"
	subpackages="$_pkgbase-$target:$targetnorm $subpackages"
done

# secfixes:
#   2.37-r0:
#     - CVE-2020-35448

build() {
	for target in $_targets; do
		workingdir="$srcdir/build-$target"
		mkdir "$workingdir"
		cd "$workingdir"
		"$builddir"/configure \
			--target=$target \
			--with-sysroot=/usr/$target \
			--prefix=/usr/ \
			--libdir=/usr/$target/lib \
			--infodir=/deleteme/info \
			--htmldir=/deleteme/html \
			--pdfdir=/deleteme/pdf \
			--mandir=/deleteme/man \
			--with-gnu-as \
			--with-gnu-ld \
			--enable-deterministic-archieves \
			--enable-interwork \
			--enable-lto \
			--enable-multilib \
			--enable-plugins \
			--enable-ld=default \
			--disable-nls
		make tooldir=/usr
	done
}

check() {
	for target in $_targets; do
		workingdir="$srcdir/build-$target"
		cd "$workingdir"
		make check
	done
}

package() {
	for target in $_targets; do
		depends="$depends $_pkgbase-$target"
	done
	mkdir -p "$pkgdir"
}

_install_subpkg() {
	target="${subpkgname#$_pkgbase-}"
	pkgdesc="Tools necessary to build programs for $target"
	workingdir="$srcdir/build-$target"
	cd "$workingdir"
	make install DESTDIR="$subpkgdir"
	rm -rf "$subpkgdir"/deleteme
	for bin in ar as nm objcopy objdump ranlib strip readelf; do
		rm -f "$subpkgdir"/usr/bin/"$bin"
	done
}

arm_none_eabi() {
	_install_subpkg
}

avr() {
	_install_subpkg
}

mips_mti_elf() {
	_install_subpkg
}

msp430_elf() {
	_install_subpkg
}

xtensa_esp32_elf() {
	_install_subpkg
}

xtensa_lx106_elf() {
	_install_subpkg
}

or1k_elf() {
	_install_subpkg
}

riscv_none_elf() {
	_install_subpkg
}

aarch64_none_elf() {
	_install_subpkg
}

sha512sums="
5df45d0bd6ddabdce4f35878c041e46a92deef01e7dea5facc97fd65cc06b59abc6fba0eb454b68e571c7e14038dc823fe7f2263843e6e627b7444eaf0fe9374  binutils-2.41.tar.xz
"
